package com.jonluo.oauth2;

import com.alibaba.fastjson.JSONObject;
import com.jonluo.common.utils.EnvVariable;
import com.jonluo.common.utils.RedisUtils;
import com.jonluo.controller.MenuController;
import com.jonluo.entity.UserEntity;
import com.jonluo.entity.UserTokenEntity;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.Date;
import java.util.Set;

/**
 * 认证
 * @author com.jonluo
 * Date 2017/9/15
 */
@Component
public class OAuth2Realm extends AuthorizingRealm {

    @Autowired
    MenuController menuController;
    @Autowired
    RestTemplate restTemplate;
    @Autowired
    EnvVariable envVariable;
    @Autowired
    RedisUtils redisUtils;

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof OAuth2Token;
    }

    /**
     * 授权(验证权限时调用)
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        UserEntity user = (UserEntity)principals.getPrimaryPrincipal();
        String userId = user.getUserId();

        //用户权限列表
        Set<String> permsSet = menuController.getUserPermissions(userId);
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setStringPermissions(permsSet);
        return info;
    }

    /**
     * 认证(登录时调用)
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String accessToken = (String) token.getPrincipal();

        //根据accessToken，查询用户信息
        UserTokenEntity tokenEntity = redisUtils.get(accessToken,UserTokenEntity.class);
        //token失效
        if(tokenEntity == null || tokenEntity.getExpireTime().getTime() < System.currentTimeMillis()){
            throw new IncorrectCredentialsException("token失效，请重新登录");
        }else {
            //当前时间
            Date now = new Date();
            //过期时间
            Date expireTime = new Date(now.getTime() + RedisUtils.DEFAULT_EXPIRE * 1000);
            //生成过token实体
            tokenEntity.setUpdateTime(now);
            tokenEntity.setExpireTime(expireTime);
            //跟新token
            redisUtils.set(tokenEntity.getToken(),tokenEntity);
        }

        //查询用户信息
        UserEntity user = null ;
        String resultJson = restTemplate.getForEntity(envVariable.getBaseUrl()+"/user/getById/"+tokenEntity.getUserId(), String.class).getBody();
        JSONObject resultMap = JSONObject.parseObject(resultJson);
        if ( 0 == resultMap.getInteger("code")){
            user = resultMap.getObject("data",UserEntity.class);
        }else {
            user = new UserEntity();
        }
        //账号锁定
        if(user.getStatus() == 0){
            throw new LockedAccountException("账号已被锁定,请联系管理员");
        }

        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, accessToken, getName());
        return info;
    }
}
